import redis
import urllib.request as ur
import time


class ProxyPool():
    def __init__(self):
        self.redis_conn =redis.StrictRedis(
            host='localhost',
            port=6379,
            decode_responses=True,
        )

    def set_proxy(self):
        # proxy = ur.urlopen('http://api.ip.data5u.com/dynamic/get.html?order=d0650d2a139e9f76aeccf4a9914b61db&random=1&sep=3').read().decode('utf-8').strip().split(' ')
        # print(proxy)
        # 设置之前的代理ip地址为None
        proxy_old=None
        while True:
            # 第一次发送请求的时候，得到代理地址，为proxy_new
            proxy_new=ur.urlopen('http://api.ip.data5u.com/dynamic/get.html?order=d0650d2a139e9f76aeccf4a9914b61db&random=1&sep=3').read().decode('utf-8').strip().split(' ')
            if proxy_new !=proxy_old:
                proxy_old=proxy_new
                # 在redis中删除键为proxy的值。本文proxy键位set类型。
                self.redis_conn.delete('proxy')
                # 把得到的代理ip值放在redis的proxy键中
                self.redis_conn.sadd('proxy',*proxy_new)
                print('更换代理为',proxy_new)
                # 延时一秒钟
                time.sleep(2)
            else:
                time.sleep(1)

    def get_proxy(self):
        # 为了防止多线程之间错误，
        proxy_s=self.redis_conn.srandmember('proxy',1)
        if proxy_s:
            return proxy_s[0]
        else:
            time.sleep(0.1)
            return self.get_proxy()

        # ret=self.redis_conn.srandmember('proxy',1)
        # print(ret)
        # print(type(ret))


if __name__ == '__main__':
    ProxyPool().set_proxy()
    # ProxyPool().get_proxy()